package com.cn.shuangzi.ad.manager;

import android.app.Activity;
import android.os.Bundle;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.kwad.sdk.api.KsRewardVideoAd;
import com.qq.e.ads.rewardvideo.RewardVideoAD;

/**
 * 激励管理类。
 */
public class AdRewardManager {

    /**
     * 激励对应的广告对象
     * 每次加载全屏视频广告的时候需要新建一个GMRewardAd，否则可能会出现广告填充问题
     */
    private TTRewardVideoAd mTTRewardVideoAd;
    private Activity mActivity;
    private TTAdNative.RewardVideoAdListener mRewardVideoListener; // 广告加载监听器
    private TTRewardVideoAd.RewardAdInteractionListener mRewardVideoAdInteractionListener; // 广告展示监听器

    private OnRewardLoadListener onRewardLoadListener;

    /**
     * 管理类构造函数
     *
     * @param activity             激励展示的Activity
     * @param onRewardLoadListener 激励加载广告回调
     */
    public AdRewardManager(Activity activity, OnRewardLoadListener onRewardLoadListener) {
        mActivity = activity;
        this.onRewardLoadListener = onRewardLoadListener;
    }

    /**
     * 获取激励广告对象
     */
    public TTRewardVideoAd getGMRewardAd() {
        return mTTRewardVideoAd;
    }

    /**
     * 先走是否初始化成功判断，再加载激励视频
     *
     * @param adUnitId 广告位ID
     */
    public void loadAd(final String adUnitId) {
        if (!TTAdManagerHolder.isInitSuccess()) {
            ADManager.getInstance().addOnAdInitDoneListener(new ADManager.OnAdInitDoneListener() {
                @Override
                public void onTTAdInitDone(boolean isSuccess) {
                    ADManager.getInstance().removeOnAdInitDoneListener(this);
                    if (isSuccess) {
                        loadAdReal(adUnitId);
                    } else {
                        if (onRewardLoadListener != null) {
                            onRewardLoadListener.onError();
                        }
                    }
                }
            });
            ADManager.getInstance().initAd(true);
        } else {
            loadAdReal(adUnitId);
        }
    }

    /**
     * 加载激励视频广告
     *
     * @param adUnitId
     */
    private void loadAdReal(String adUnitId) {
        if(mActivity == null){
            if(onRewardLoadListener!=null){
                onRewardLoadListener.onError();
            }
            return;
        }
        ADManager.getInstance().clearCurrentReward();
        /** 1、创建AdSlot对象 */
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(adUnitId)
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = TTAdManagerHolder.getInstance().createAdNative(mActivity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        /** 4、加载广告 */
        adNativeLoader.loadRewardVideoAd(adslot, mRewardVideoListener);
    }

    // 广告加载成功后，开始展示广告
    private void showRewardVideoAd() {

        if (onRewardLoadListener != null) {
            onRewardLoadListener.onShow();
        }

        if (mTTRewardVideoAd == null) {
            ADUtil.logError("请先加载广告或等待广告加载完毕后再调用show方法");
            return;
        }
        /** 5、设置展示监听器，展示广告 */
        mTTRewardVideoAd.setRewardAdInteractionListener(mRewardVideoAdInteractionListener);
        mTTRewardVideoAd.showRewardVideoAd(mActivity);
    }

    private void initListeners() {
        // 广告加载监听器
        this.mRewardVideoListener = new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int i, String s) {

                if (onRewardLoadListener != null) {
                    onRewardLoadListener.onError();
                }
                ADUtil.logError("激励视频 reward load fail: errCode: " + i + ", errMsg: " + s);
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                ADUtil.logError("激励视频 reward load success");
                mTTRewardVideoAd = ttRewardVideoAd;
                showRewardVideoAd();
            }

            @Override
            public void onRewardVideoCached() {
                ADUtil.logError("激励视频 reward cached success");
            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                ADUtil.logError("激励视频 reward cached success 2");
                mTTRewardVideoAd = ttRewardVideoAd;
                showRewardVideoAd();
            }
        };
        // 广告展示监听器
        this.mRewardVideoAdInteractionListener = new TTRewardVideoAd.RewardAdInteractionListener() {
            boolean isRewardValid;
            @Override
            public void onAdShow() {
                ADUtil.logError("激励视频 reward show");

                MediationAdEcpmInfo gmAdEcpmInfo = mTTRewardVideoAd.getMediationManager().getShowEcpm();
                ADUtil.logError("展示的激励视频广告信息： adSdkName: " + gmAdEcpmInfo.getSdkName() + "   CustomSdkName：" + gmAdEcpmInfo.getCustomSdkName() + "   Ecpm: " + gmAdEcpmInfo.getEcpm());

                if (gmAdEcpmInfo != null) {
                    if (!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())) {
                        RewardVideoAD rewardVideoAD = ADManager.getInstance().getYlhRewardAd();
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getRewardYlhErrorInfo();
                        ADUtil.logError("ylhErrorInfo:" + ylhErrorInfo + "|rewardVideoAD:" + rewardVideoAD);
                        if (rewardVideoAD != null && ylhErrorInfo != null) {
                            int ecpm = getReportEcmp(rewardVideoAD.getECPM(), gmAdEcpmInfo.getEcpm());
                            rewardVideoAD.sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                            ADUtil.logError("上报优量汇 激励视频 竞价失败：ecpm=" + ecpm + "，" + ylhErrorInfo);
                        }
                    }
                    if (!ADManager.getInstance().isKsPlatform(gmAdEcpmInfo.getSdkName())) {
                        KsRewardVideoAd ksRewardVideoAd = ADManager.getInstance().getKsRewardAd();
                        KsErrorInfo ksErrorInfo = ADManager.getInstance().getRewardKsErrorInfo();
                        ADUtil.logError("ksErrorInfo:" + ksErrorInfo + "|ksRewardVideoAd:" + ksRewardVideoAd);
                        if (ksErrorInfo != null && ksRewardVideoAd != null) {
                            if (ksErrorInfo.getAdExposureFailedReason() != null) {
                                ksErrorInfo.getAdExposureFailedReason().setWinEcpm(getReportEcmp(ksRewardVideoAd.getECPM(), gmAdEcpmInfo.getEcpm()))
                                        .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                            }
                            ksRewardVideoAd.reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(), ksErrorInfo.getAdExposureFailedReason());
                            ADUtil.logError("上报快手 激励视频 竞价失败：" + ksErrorInfo);
                        }
                    }
                }
            }

            @Override
            public void onAdVideoBarClick() {
                ADUtil.logError("激励视频 reward click");
            }

            @Override
            public void onAdClose() {
                ADUtil.logError("激励视频 reward close");
                if (onRewardLoadListener != null) {
                    onRewardLoadListener.onClose(isRewardValid);
                    onRewardLoadListener = null;
                }
                destroy();
            }

            @Override
            public void onVideoComplete() {
                ADUtil.logError("激励视频 reward onVideoComplete");
            }

            @Override
            public void onVideoError() {
                ADUtil.logError("激励视频 reward onVideoError");
                if (onRewardLoadListener != null) {
                    onRewardLoadListener.onError();
                }
            }

            @Override
            public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {
                ADUtil.logError("激励视频 reward onRewardVerify");
            }

            @Override
            public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                this.isRewardValid = isRewardValid;
                ADUtil.logError("激励视频 reward onRewardArrived");
                if (onRewardLoadListener != null) {
                    onRewardLoadListener.onRewardArrived(isRewardValid, rewardType, extraInfo);
                }
            }

            @Override
            public void onSkippedVideo() {
                ADUtil.logError("激励视频 reward onSkippedVideo");
                if (onRewardLoadListener != null) {
                    onRewardLoadListener.onClose(isRewardValid);
                    onRewardLoadListener = null;
                }
            }
        };
    }

    private int getReportEcmp(int lossEcpm, String winEcpm) {
        int ecpm = lossEcpm;
        try {
            if (ecpm <= 0) {
                ecpm = 50 * ADConst.YUAN;
            }
            double preEcpm = Double.parseDouble(winEcpm);
            if (preEcpm > 0) {
                int addCPM = ADUtil.getRandom(30*ADConst.YUAN,5*ADConst.YUAN);
                ecpm = (int) (preEcpm + addCPM);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ecpm;
    }

    public void destroy() {
        ADUtil.logError("=========销毁当前激励视频========");
        if (mTTRewardVideoAd != null && mTTRewardVideoAd.getMediationManager() != null) {
            mTTRewardVideoAd.getMediationManager().destroy();
        }
    }

    public interface OnRewardLoadListener {

        void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo);

        void onError();

        void onShow();

        void onClose(boolean isRewardValid);
    }
}
